package vboot.core.module.ass.oss.root;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import org.hibernate.service.spi.ServiceException;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import vboot.core.common.exception.base.BaseException;
import vboot.core.common.utils.file.FileUtils;
import vboot.core.common.utils.ruoyi.StringUtils;
import vboot.core.module.ass.oss.file.AssOssFile;
import vboot.core.common.utils.lang.IdUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AssOssRemoteHand {

    public AssOssFile upload(MultipartFile file,String md5) {
        String originalfileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
        OssClient storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
        } catch (IOException e) {
            throw new BaseException(e.getMessage());
        }
        // 保存文件信息
        AssOssFile ossFile = new AssOssFile();
        ossFile.setId(IdUtils.getUID());
        ossFile.setZsize(file.getSize());
        ossFile.setMd5(md5);
        ossFile.setPath(uploadResult.getUrl());
        ossFile.setService(storage.getConfigKey());
        return ossFile;
    }

    public void download(HttpServletRequest request, HttpServletResponse response,
                         String fileName, String path) throws IOException {
//        response.reset();
        FileUtils.setAttachmentResponseHeader(response, fileName);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");
        long data;
        try {
            data = HttpUtil.download(path, response.getOutputStream(), false);
        } catch (HttpException e) {
            if (e.getMessage().contains("403")) {
                throw new ServiceException("无读取权限, 请在对应的OSS开启'公有读'权限!");
            } else {
                throw new ServiceException(e.getMessage());
            }
        }
        response.setContentLength(Convert.toInt(data));
    }

}
